import React from 'react';
import Loading from '../../components/Loading/loading.jsx';
import './scrollView.scss';
/**
 * <ScrollView loadCallback={function} isend={bool}/>
 * @description 滚动加载组件
 */
import { connect } from 'react-redux';

class ScrollView extends React.Component {
    constructor(props) {
        super(props);
        this._onLoadPage = this.onLoadPage.bind(this);
        this.isStart = false;
    }
    onLoadPage(){
        let clientHeight = document.documentElement.clientHeight;
        let scrollHeight = document.body.scrollHeight;
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        let proLoadDis = 30;
        if ((scrollTop + clientHeight) >= (scrollHeight - proLoadDis)) {
            if (!this.props.isend) {
              // if(this.isStart) {
              //   setTimeout(() => {
              //     this.props.loadCallback && this.props.loadCallback();
              //   }, 50)
              // }

                // 通过reudx监听是否正在执行异步加载数据，防止一次性请求多页数据
                if (!this.props.readyToLoad) {
                    return;
                }
                this.props.loadCallback && this.props.loadCallback();
              // this.isStart = true;
            }
        }
    }

    componentDidMount(){
        window.addEventListener('scroll', this._onLoadPage);
    }
    componentWillUnmount(){
        window.removeEventListener('scroll', this._onLoadPage);
    }
    render(){
        return (
            <div className="scrollview">
                {this.props.children}
                <Loading isend={this.props.isend}/>
            </div>
        );

    }
}


export default connect(
    state =>({
        readyToLoad: state.scrollViewReducer.readyToLoad,
    })
)(ScrollView)
